import { StorageData, Contact, Category, Settings } from '../types';

const STORAGE_KEY = 'favorflow_data';

// 默认设置
const DEFAULT_SETTINGS: Settings = {
  id: '1',
  autoBackup: true,
  backupFrequency: 7,
  createTime: new Date().toISOString(),
  updateTime: new Date().toISOString()
};

// 默认数据
const DEFAULT_DATA: StorageData = {
  contacts: [],
  categories: [],
  settings: DEFAULT_SETTINGS
};

// 存储适配器
const storage = {
  getItem(key: string): string | null {
    try {
      return uni.getStorageSync(key);
    } catch (error) {
      console.error('获取存储数据失败:', error);
      return null;
    }
  },
  setItem(key: string, value: string): void {
    try {
      uni.setStorageSync(key, value);
    } catch (error) {
      console.error('保存存储数据失败:', error);
      throw error;
    }
  },
  removeItem(key: string): void {
    try {
      uni.removeStorageSync(key);
    } catch (error) {
      console.error('删除存储数据失败:', error);
      throw error;
    }
  }
};

class StorageManager {
  // 获取所有数据
  static async getAllData(): Promise<StorageData> {
    try {
      const data = storage.getItem(STORAGE_KEY);
      console.log('【存储】获取所有数据原始结果:', data);
      const parsedData = data ? JSON.parse(data) : DEFAULT_DATA;
      console.log('【存储】获取所有数据解析结果:', parsedData);
      return parsedData;
    } catch (error) {
      console.error('【存储】获取数据失败:', error);
      return DEFAULT_DATA;
    }
  }

  // 保存所有数据
  static async saveAllData(data: StorageData): Promise<void> {
    try {
      console.log('【存储】保存所有数据:', data);
      storage.setItem(STORAGE_KEY, JSON.stringify(data));
    } catch (error) {
      console.error('【存储】保存数据失败:', error);
      throw error;
    }
  }

  // 获取存储信息
  static async getStorageInfo(): Promise<{ currentSize: number; limitSize: number }> {
    return new Promise((resolve, reject) => {
      try {
        uni.getStorageInfo({
          success: (res) => {
            console.log('【存储】获取存储信息成功:', res);
            resolve({
              currentSize: res.currentSize,
              limitSize: res.limitSize
            });
          },
          fail: (err) => {
            console.error('【存储】获取存储信息失败:', err);
            reject(err);
          }
        });
      } catch (error) {
        console.error('【存储】获取存储信息异常:', error);
        reject(error);
      }
    });
  }

  // 获取联系人列表
  static async getContacts(): Promise<Contact[]> {
    const data = await this.getAllData();
    console.log('【存储】获取联系人列表:', data.contacts);
    return data.contacts;
  }

  // 保存联系人
  static async saveContact(contact: Contact): Promise<void> {
    console.log('【存储】保存联系人:', contact);
    const data = await this.getAllData();
    const index = data.contacts.findIndex(c => c.id === contact.id);
    if (index > -1) {
      console.log('【存储】更新已存在联系人, 索引:', index);
      data.contacts[index] = contact;
    } else {
      console.log('【存储】添加新联系人');
      data.contacts.push(contact);
    }
    await this.saveAllData(data);
    console.log('【存储】联系人保存完成');
  }

  // 删除联系人
  static async deleteContact(id: string): Promise<void> {
    console.log('【存储】删除联系人:', id);
    const data = await this.getAllData();
    const originalLength = data.contacts.length;
    data.contacts = data.contacts.filter(c => c.id !== id);
    console.log(`【存储】联系人删除结果: 删除前 ${originalLength} 个, 删除后 ${data.contacts.length} 个`);
    await this.saveAllData(data);
  }

  // 获取分类列表
  static async getCategories(): Promise<Category[]> {
    const data = await this.getAllData();
    return data.categories;
  }

  // 保存分类
  static async saveCategory(category: Category): Promise<void> {
    const data = await this.getAllData();
    const index = data.categories.findIndex(c => c.id === category.id);
    if (index > -1) {
      data.categories[index] = category;
    } else {
      data.categories.push(category);
    }
    await this.saveAllData(data);
  }

  // 删除分类
  static async deleteCategory(id: string): Promise<void> {
    const data = await this.getAllData();
    data.categories = data.categories.filter(c => c.id !== id);
    await this.saveAllData(data);
  }

  // 获取设置
  static async getSettings(): Promise<Settings> {
    const data = await this.getAllData();
    return data.settings;
  }

  // 保存设置
  static async saveSettings(settings: Settings): Promise<void> {
    const data = await this.getAllData();
    data.settings = settings;
    await this.saveAllData(data);
  }

  // 清除所有数据
  static async clearAllData(): Promise<void> {
    try {
      storage.removeItem(STORAGE_KEY);
    } catch (error) {
      console.error('清除数据失败:', error);
      throw error;
    }
  }
}

export default StorageManager; 